<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:order:soRds:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <Tabs v-model:activeKey="activeKey" tabPosition="left">
      <Tabs.TabPane
        v-for="(item, index) in formTabs"
        :key="index"
        :forceRender="true"
        :tab="item.tabName"
      >
        <SingleForm
          v-if="flag"
          :schemas="item.colList"
          :formConfig="formConfig"
          :data="record"
          ref="singleFormArr"
        />
      </Tabs.TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderSaleFormTabs',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';

  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { formSet } from '/@/api/test/testData';
  // import {
  //   WecharCusInvPriceRoute,
  //   wecharCusInvPriceRouteSave,
  //   wecharCusInvPriceRouteForm,
  // } from '/@/api/setting/price/wecharCusInvPriceRoute';
  import { SoRds, soRdsSave, soRdsForm, splitRow } from '/@/api/shop/order/soRds';

  import SingleForm from './singleForm.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.order.sale');
  const { showMessage } = useMessage();
  const record = ref<SoRds>({} as SoRds);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数据') : t('编辑数据'),
  }));

  let formTabs = ref<any>([]);
  let formConfig = ref<any>({});
  let row = ref<any>();

  let flag = ref(false);

  const activeKey = ref<number>(0);

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    flag.value = false;
    activeKey.value = 0;
    setDrawerProps({ loading: true });
    row.value = data.ope;

    const res11 = await formSet({ viewCode: 'shop_order_rds_form001' });

    formTabs.value = res11.layVoucherView.formTabs;
    formConfig.value = res11.layVoucherView.formConfig;
    if (data.ope === '1') {
      // 拆行
      formTabs.value.forEach((item) => {
        item.colList.forEach((col) => {
          col.formDynamicDisable = '1';
          if (col.formField === 'inum') {
            col.formDynamicDisable = '0';
          }
          if (col.formField === 'iquantity') {
            col.formDynamicDisable = '0';
          }
          if (col.formField === 'itaxunitprice') {
            col.formDefaultValue = '0.00';
          }
          if (col.formField === 'isum') {
            col.formDefaultValue = '0.00';
          }
          if (col.formField === 'idiscount') {
            col.formDefaultValue = '0.00';
          }
          if (col.formField === 'cbdefine2') {
            col.formDefaultValue = '0.00';
          }
          if (col.formField === 'cbdefine1') {
            col.formDynamicDisable = '0';
          }
          if (col.formField === 'bodyVO.cdefine22') {
            col.formDynamicDisable = '0';
          }
        });
      });
    }
    if (data.ope === '2') {
      // 新增赠品
      formTabs.value.forEach((item) => {
        item.colList.forEach((col) => {
          col.formDynamicDisable = '1';
          if (col.formField === 'bgift') {
            col.formDynamicDisable = '0';
          }
          if (col.formField === 'basInv.cinvcode') {
            col.formDynamicDisable = '0';
            col.formIsRequired = '1';
          }
          if (col.formField === 'inum') {
            col.formDynamicDisable = '0';
            col.formIsRequired = '1';
          }
          if (col.formField === 'iquantity') {
            col.formDynamicDisable = '0';
            col.formIsRequired = '1';
          }
          if (col.formField === 'bodyVO.cdefine22') {
            col.formDynamicDisable = '0';
          }
          if (col.formField === 'cmemo') {
            col.formDynamicDisable = '0';
          }
        });
      });
    }

    const res = await soRdsForm(data);
    record.value = (res.soRds || {}) as SoRds;
    record.value.__t = new Date().getTime();
    record.value.ope = data.ope;
    flag.value = true;

    setDrawerProps({ loading: false });
  });
  let singleFormArr = ref<any>([]);

  async function handleSubmit() {
    let obj = {};
    let falg = false;
    await singleFormArr.value.forEach((item) => {
      item.validateForm().then((e) => {
        if (!e) {
          falg = true;
        } else {
          obj = { ...obj, ...e };
        }
      });
    });
    setTimeout(async () => {
      if (falg) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      } else {
        try {
          if (row.value === '1') {
            setDrawerProps({ confirmLoading: true });
            const params: any = {
              isNewRecord: record.value.isNewRecord,
              id: record.value.id,
            };
            const res = await splitRow(params, obj);
            showMessage(res.message);
            setDrawerProps({ confirmLoading: false });
            setTimeout(closeDrawer);
            emit('success', obj);
          } else {
            setDrawerProps({ confirmLoading: true });
            const params: any = {
              isNewRecord: record.value.isNewRecord,
              id: record.value.id,
            };
            const res = await soRdsSave(params, obj);
            showMessage(res.message);
            setDrawerProps({ confirmLoading: false });
            setTimeout(closeDrawer);
            emit('success', obj);
          }
        } catch (error: any) {
          // if (error && error.errorFields) {
          //   showMessage('您填写的信息有误，请根据提示修正。');
          // }
          console.log('error', error);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
    }, 0);
  }
</script>
